package tv.youxing.android.ui;

import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.text.NumberFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.DownloadInfoModel;
import tv.youxing.android.ui.test.test3DownloadListener;
import tv.youxing.android.utils.PicassoUtils;

/**
 * Created by Administrator on 2017/7/2.
 * 下载的详情页
 */

public class DownInfoDesActivity extends BaseActivity {


    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.downloadSize)
    TextView downloadSize;
    @BindView(R.id.tvProgress)
    TextView tvProgress;
    @BindView(R.id.netSpeed)
    TextView netSpeed;
    @BindView(R.id.pbProgress)
    ProgressBar pbProgress;
    @BindView(R.id.start)
    Button download;
    @BindView(R.id.remove)
    Button remove;
    @BindView(R.id.restart)
    Button restart;


    private NumberFormat numberFormat;
    private DownloadTask task;
    private DownloadInfoModel apk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_info_des);
        ButterKnife.bind(this);

        apk = (DownloadInfoModel) getIntent().getSerializableExtra("apk");
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);


        // 写法一：从内存中获取
        if (OkDownload.getInstance().hasTask(apk.url)) {
            task = OkDownload.getInstance().getTask(apk.url)//
                    .register(new DesListener("DesListener"))//
                    .register(new test3DownloadListener());
        }


        PicassoUtils.loadImageView(this, apk.url, icon);
        name.setText(apk.name);
        if (task != null) refreshUi(task.progress);
    }


    private void refreshUi(Progress progress) {
        String currentSize = Formatter.formatFileSize(this, progress.currentSize);
        String totalSize = Formatter.formatFileSize(this, progress.totalSize);
        downloadSize.setText(currentSize + "/" + totalSize);
        String speed = Formatter.formatFileSize(this, progress.speed);
        netSpeed.setText(String.format("%s/s", speed));
        tvProgress.setText(numberFormat.format(progress.fraction));
        pbProgress.setMax(10000);
        pbProgress.setProgress((int) (progress.fraction * 10000));
        switch (progress.status) {
            case Progress.NONE:
                download.setText("下载");
                break;
            case Progress.LOADING:
                download.setText("暂停");
                break;
            case Progress.PAUSE:
                download.setText("继续");
                break;
            case Progress.WAITING:
                download.setText("等待");
                break;
            case Progress.ERROR:
                download.setText("出错");
                break;
            case Progress.FINISH:
                download.setText("下载完成");
//                    if (ApkUtils.isAvailable(this, new File(progress.filePath))) {
//                        download.setText("卸载");
//                    } else {
//                        download.setText("安装");
//                    }
                break;
        }
    }


    @OnClick({R.id.start, R.id.remove, R.id.restart})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.start:
                download();
                break;
            case R.id.remove:
                remove();
                break;
            case R.id.restart:
                restart();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.unRegister("DesListener");
        }
    }



    void download() {

        System.out.println("开始下载");

        if (task == null) {

            //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
            GetRequest<File> request = OkGo.<File>get(apk.url)//
                    .headers("aaa", "111")//
                    .params("bbb", "222");

            task = OkDownload.request(apk.url, request)//
                    .priority(apk.priority)//
                    .extra1(apk)//
                    .register(new DesListener("DesListener"))//
                    .register(new test3DownloadListener());
        }
        switch (task.progress.status) {
            case Progress.PAUSE:
            case Progress.NONE:
            case Progress.ERROR:
                task.start();
                break;
            case Progress.LOADING:
                task.pause();
                break;
            case Progress.FINISH:
                CustomToast.INSTANCE.showToast("下载完成");
                File file = new File(task.progress.filePath);
//                if (ApkUtils.isAvailable(this, file)) {
//                    ApkUtils.uninstall(this, ApkUtils.getPackageName(this, file.getAbsolutePath()));
//                } else {
//                    ApkUtils.install(this, file);
//                }
                break;
        }
    }

    void remove() {
        if (task != null) task.remove();
        downloadSize.setText("--M/--M");
        netSpeed.setText("---/s");
        tvProgress.setText("--.--%");
        pbProgress.setProgress(0);
        download.setText("下载");
    }

    void restart() {
        if (task != null) task.restart();
    }

    class DesListener extends DownloadListener {

        DesListener(String tag) {
            super(tag);
        }

        @Override
        public void onStart(Progress progress) {
            System.out.println("2:onStart");
        }

        @Override
        public void onProgress(Progress progress) {
            System.out.println("2:onProgress");
            refreshUi(progress);
        }

        @Override
        public void onFinish(File file, Progress progress) {
        }

        @Override
        public void onRemove(Progress progress) {
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
            System.out.println("2:error");
        }
    }
}